package cn.chainfind.common.utils.sms;

import cn.chainfind.common.utils.StringUtils;
import cn.chainfind.common.utils.http.HttpUtils;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: zcb
 * @email: zcbin2@grgbanking.com
 * @time: 2021/11/16 10:35 上午
 * @version: 1.0
 * @desc:
 * 阿里云api sms地址
 * https://market.console.aliyun.com/imageconsole/index.htm?#/bizlist?_k=1xyo9l
 */
public class SmsUtils {
    private static final Logger log = LoggerFactory.getLogger(SmsUtils.class);

    public static final String host = "https://aliapi.market.alicloudapi.com";
    public static final String path = "/smsApi/verifyCode/send";
    public static final String appcode = "d0e24cbe365c4b9da68333ca3e4ce786";

    public static void main(String[] args) {
        sendSms("13405995634","677856");
    }



    private static boolean sendSms(String phone,String captcha){

        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("phone", phone);
        querys.put("templateId", "540");
        querys.put("variables", "1234");
        Map<String, String> bodys = new HashMap<String, String>();


        try {

            String response = HttpUtils.sendPost(host+path,map2Str(querys));
            System.out.println(response.toString());
            if (StringUtils.isEmpty(response))
            {
                log.error("发送短信异常 {}验证码{}", phone,captcha);
                return false;
            }
            JSONObject obj = JSONUtil.parseObj(response);
            String status = obj.getStr("returnStatus");
            String message = obj.getStr("message");
            if (status.trim().equals("1")){
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 拼接Map key1=value1&key2=value2
     * @param map
     * @return
     */
    public static String map2Str(Map<String, String> map) {
        if (map == null || map.size() == 0) {
            return "";
        }

        String buffer = "";
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String temp = entry.getKey() + "=" + entry.getValue() + "&";
            buffer += temp;
        }
        return buffer.substring(0, buffer.length() - 1);
    }
}
